package nginx

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"net/http"
	"strings"
	"utility/common"
)

type Nginx struct {
	Version     string
	DownLoadUrl string
	InstallPath string
}

const (
	NgxOfficialUrl = "https://nginx.org"
)

func (c *Nginx) GetCurrentStableVersion() (err error) {

	resp, err := http.Get("https://nginx.org/en/download.html")
	if err != nil {
		return
	}
	defer resp.Body.Close()
	dom, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return err
	}
	dom.Find("#content").Each(func(i int, selection *goquery.Selection) {
		var theSelection *goquery.Selection
		selection.Find("center").Each(func(i int, selection *goquery.Selection) {
			text := selection.Text()
			if text == "Stable version" {
				theSelection = selection
				return
			}
		})
		ngxStableSelection := theSelection.Next()
		if ngxStableSelection != nil {
			ngxStableSelection.Find("a").Each(func(i int, selection *goquery.Selection) {
				text := selection.Text()
				if strings.Contains(text, "nginx") && !strings.Contains(text, "Windows") {
					fmt.Println(selection.Html())
					text = selection.Text()
					c.Version = text
					url, exist := selection.Attr("href")
					if exist {
						if strings.HasPrefix(url, "/") {
							url := "https://nginx.org" + url
							c.DownLoadUrl = url
						}
					}
				}
			})
		}
	})

	return

}

func (c *Nginx) Install() {
	if c.InstallPath == "" {
		c.InstallPath = "/usr/local/nginx"
	}
	c.GetCurrentStableVersion()

	// 开始执行安装Nginx

}
func (c *Nginx) GenBashScript() {
	var lines []string
	lines = append(lines, "#!/usr/bin/env bash")
	lines = append(lines, "#!/usr/bin/env bash")
	lines = append(lines, "#!/usr/bin/env bash")
	lines = append(lines, "#!/usr/bin/env bash")
	lines = append(lines, "#!/usr/bin/env bash")
	lines = append(lines, "#!/usr/bin/env bash")
	lines = append(lines, "#!/usr/bin/env bash")
	line := fmt.Sprintf(``, c.InstallPath)
	bashPath := "/tmp/installNginx.sh"
	common.WriteLines(lines, bashPath)
}
